<template>
  <el-dialog
    v-if="reload"
    :title="title"
    :visible.sync="dialogFormVisible"
    width="650px"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      :status-icon="true"
      label-width="100px"
    >
      <el-form-item
        v-if="user.level < 3"
        label="所属村"
        prop="village"
      >
        <el-cascader
          v-model="form.villageWrap"
          :options="villageCascader"
          :props="villageProp"
          placeholder="请选择所属村"
          clearable
          @change="villageChange"
        />
      </el-form-item>
      <el-form-item
        label="所属组"
        prop="group"
      >
        <el-select
          v-model.number="form.group"
          placeholder="请选择所属组"
          clearable
        >
          <el-option
            v-for="item in groupAtt"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="补助项"
        prop="subsidy"
      >
        <el-cascader
          v-model="form.subsidyWrap"
          :options="subsidyCascader"
          placeholder="请选择补助项"
          :props="props"
          clearable
          @change="subsidyChange"
        />
      </el-form-item>

      <el-form-item
        label="是否是补助个人"
        prop="personal"
      >
        <el-select
          v-model.number="form.personal"
          placeholder="请选择是否属于补助个人"              
        >
          <el-option
            label="是"
            :value="true"
          />
          <el-option
            label="否"
            :value="false"
          />
        </el-select>
      </el-form-item>

      <!-- 补助对象 或 补助户 信息 -->
      <el-form-item
        :label="form.personal ? '补助个人姓名': '补助户'"
        prop="name"
      >
        <el-input
          v-model="form.name"
          placeholder="请输入村民(补助对象或补助户)姓名"
          clearable
        />
      </el-form-item>
      <el-form-item
        v-if="form.personal"
        label="性别"
        prop="sex"
      >
        <el-select
          v-model.number="form.sex"
          placeholder="请选择性别"
          clearable
        >
          <el-option
            label="男"
            :value="0"
          />
          <el-option
            label="女"
            :value="1"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.personal"
        label="民族"
        prop="nation"
      >
        <el-select
          v-model.number="form.nation"
          placeholder="请选择所属民族"
          clearable
        >
          <el-option
            v-for="(item, index) in nationAtt"
            :key="index"
            :label="item"
            :value="index + 1"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="form.personal"
        label="手机号"
        prop="phone"
      >
        <el-input
          v-model="form.phone"
          placeholder="请输入手机号"
          clearable
        />
      </el-form-item>
      <el-form-item
        v-if="form.personal"
        label="身份证号"
        prop="identityNumber"
      >
        <el-input
          v-model="form.identityNumber"
          placeholder="请输入村民身份证号"
          clearable
        />
      </el-form-item>
      <el-form-item
        label="家庭地址"
        prop="address"
      >
        <el-input
          v-model="form.address"
          :placeholder="form.personal ? '请输入村民家庭地址': '请输入补助户家庭地址'"
          clearable
        />
      </el-form-item>
      <!-- 补助对象 或 补助户 信息 -->

      <el-form-item
        label="申请时间"
        prop="applicationTime"
      >
        <el-date-picker
          v-model="form.applicationTime"
          align="right"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择申请时间"
          :picker-options="pickerOptions1"
          clearable
        />
      </el-form-item>
      <el-form-item
        label="补助原因"
        prop="cause"
      >
        <el-input
          v-model="form.cause"
          type="textarea"
          :rows="5"
          placeholder="请输入补助原因"
          clearable
        />
      </el-form-item>
      <el-form-item
        label="备注信息"
        prop="remarks"
      >
        <el-input
          v-model="form.remarks"
          type="textarea"
          :rows="5"
          placeholder="请输入备注信息 -> 不同对象 补助信息 的附加说明"
          clearable
        />
      </el-form-item>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="close">
        取 消
      </el-button>
      <el-button
        type="primary"
        @click="save"
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
export default {
  name: "TableEdit",
  props: ["fetchData"],
  data() {
    return {
      form: {
        villageWrap: [],
        personal: true,
        village: "",
        group: "",
        subsidyWrap: [],
        subsidy: "",
        // applicationTime: "",
        remarks: "",
        cause: "",
        villagerInfo: {
          name: "",
          //性别
          sex: 0,
          //民族
          nation: 1,
          //手机号
          // phone: "",
          //身份证号
          identityNumber: "",
          //籍贯
          address: "",
        },
      },
      id: null,
      created: true,
      rules: {
        village: [{ required: true, trigger: "change", message: "请选择所属村" }],
        group: [{ required: false, trigger: "change", message: "请选择所属组" }],
        subsidy: [{ required: true, trigger: "change", message: "请选择补助项" }],
        personal: [{ required: true, trigger: "change", message: "请选择补助对象或者补助户" }],
        applicationTime: [{ required: false, trigger: "change", message: "请选择申请时间" }],
        cause: [{ required: false, trigger: "blur", message: "请输入补助原因" }],
        remarks: [{ required: false, trigger: "blur", message: "请输入备注信息" }],
        'name': [
          { required: true, message: "请输入村民(补助对象或补助户)姓名", trigger: "blur" }
        ],
        'sex': [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
        'nation': [
          { required: true, message: "请选择所属民族", trigger: "change" }
        ],
        'phone': [
          {
                required: false, message: "请填写手机号", trigger: "blur"
          }
        ],
        'identityNumber': [
          {
                required: false, message: "请填写身份证号", trigger: "blur"
          }
        ],
        'address': [
          {
                required: false, message: "请填写地址", trigger: "blur"
          }
        ],
      },

      nationAtt: [
        "汉族",
        "蒙古族",
        "回族",
        "藏族",
        "维吾尔族",
        "苗族",
        "彝族",
        "壮族",
        "布依族",
        "朝鲜族",
        "满族",
        "侗族",
        "瑶族",
        "白族",
        "土家族",
        "哈尼族",
        "哈萨克族",
        "傣族",
        "黎族",
        "傈僳族",
        "佤族",
        "畲族",
        "高山族",
        "拉祜族",
        "水族",
        "东乡族",
        "纳西族",
        "景颇族",
        "柯尔克孜族",
        "土族",
        "达斡尔族",
        "仫佬族",
        "羌族",
        "布朗族",
        "撒拉族",
        "毛南族",
        "仡佬族",
        "锡伯族",
        "阿昌族",
        "普米族",
        "塔吉克族",
        "怒族",
        "乌孜别克族",
        "俄罗斯族",
        "鄂温克族",
        "德昂族",
        "保安族",
        "裕固族",
        "京族",
        "塔塔尔族",
        "独龙族",
        "鄂伦春族",
        "赫哲族",
        "门巴族",
        "珞巴族",
        "基诺族",
      ],
      title: "",
      dialogFormVisible: false,
      props: {
        value: "id",
        label: "name",
        children: "subsidy",
      },
      subsidyCascader: [],
      villageCascader: [],
      villageProp: {
        value: "id",
        label: "name",
      },
      groupAtt: [],
      pickerOptions1: {
        disabledDate(time) {
          return false;
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      reload: true,
      reset: false,

      createForm: {},
    };
  },
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  watch: {
  },
  created() {
    this.init();
  },
  methods: {
    showEdit(row) {
      if (!row) {
        this.title = "添加";
        this.created = true;
      } else {
        this.id = row.id;
        this.fetch(this.id);
        this.title = "编辑";
        this.form = Object.assign({}, row);
        this.created = false;
      }
      this.dialogFormVisible = true;
    },
    close() {
      let { village } = this.form
      this.$refs["form"].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      if(this.user.level == 3) {
        this.form.village = village
      }
    },
    save() {
      this.$refs["form"].validate((valid) => {
        this.createForm = JSON.parse(JSON.stringify(this.form))
        this.clearNullField(this.createForm, 'group')
        if (valid) {
          if (this.created) {
            this.create();
          } else {
            this.edit();
          }
        } else {
          return false;
        }
      });
    },
    async create() {
      const res = await this.$http.post(`/subsidy-info`, this.createForm);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$emit("fetchData");
        this.close()
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      const res = await this.$http.put(`/subsidy-info/${this.id}`, this.createForm);
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$emit("fetchData");
        this.close()
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    async fetch(id) {
      const res = await this.$http.get(`subsidy-info/${id}?join=subsidy&join=subsidyType&join=village&join=group`);

      //处理关联
      // res.data.village = res.data.village.id;
      // res.data.villager = res.data.villager.id;
      res.data.subsidy = res.data.subsidy.id;
      res.data.subsidyType = res.data.subsidyType.id;
      const town = await this.$http.get(`village/${res.data.village.id}?join=town`);

      const area = await this.$http.get(`town/${town.data.town.id}?join=area`);

      res.data.villageWrap = [
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ];

      res.data.subsidyWrap = [res.data.subsidyType, res.data.subsidy]
      // 先拿到 villageWrap villageChange 使用
      this.form = Object.assign({}, res.data);

      this.villageChange([
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ], true);
      // res.data.subsidyWrap = [res.data.subsidyType, res.data.subsidy];
      // 后拿到 subsidyWrap 数据注册 使用
      // this.form = Object.assign({}, res.data);
      this.subsidyChange([res.data.subsidyType, res.data.subsidy])
      this.form.group = res.data.group.id
      // this.form.subsidyWrap = [res.data.subsidyType, res.data.subsidy];

      // this.town =
    },
    async init() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      res.data.forEach(area => {
        area.children = area.town
        area.town.forEach(town => {
          town.children = town.village
        })
      })
      this.villageCascader = res.data;
      this.setSelectItem()
    },
    async villageChange(val, first) {
      this.form.village = val[val.length - 1];
      this.form.group = ""
      if(!first) {
        this.form.subsidy = "";
        this.form.subsidyWrap = [];  
      }
      const res = await this.$http.get(`village/${this.form.village}?join=group&join=subsidyType&join=subsidyType.subsidy`);
      this.subsidyCascader = res.data.subsidyType;
      this.groupAtt = res.data.group
    }, 
    subsidyChange(val) {
      this.form.subsidy = val[1];
      this.form.subsidyType = val[0];
    },

    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } 
        else if (this.user.level == 3) {
         //村级
        this.form.village = this.user.village.id
        this.villageChange([this.form.village])
      } 
    },
  },
};
</script>
